package com.renchunlin.taobaounion.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.renchunlin.taobaounion.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 * class title:
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/1/29.
 * PS: Not easy to write code, please indicate.
 */
public class TextFlowLayout extends ViewGroup {

    private List<String> mTextList = new ArrayList<>();
    public static final float DEFAULT_SPACE = 10;
    private float mItemHorizontalSpace = DEFAULT_SPACE;
    private float mItemVerticalSpace = DEFAULT_SPACE;
    private int selfWidth;
    private int itemHeight;
    private OnFlowTextItemClickListener onFlowTextItemClickListener;

    public TextFlowLayout(Context context) {
        this(context, null);
    }

    public TextFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        //去拿到相关属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FlowTextStyle);
        mItemHorizontalSpace = typedArray.getDimension(R.styleable.FlowTextStyle_horizontalSpace, DEFAULT_SPACE);
        mItemVerticalSpace = typedArray.getDimension(R.styleable.FlowTextStyle_verticalSpace, DEFAULT_SPACE);
        typedArray.recycle();
    }

    //描述所有行
    private List<List<View>> lists = new ArrayList<>();

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getChildCount() == 0) {
            return;
        }
        //描述单行
        List<View> line = null;
        lists.clear();
        selfWidth = MeasureSpec.getSize(widthMeasureSpec);
        Log.i("chen", "selfWidth: " + selfWidth);
        //测量
        //Log.i("chen", "测量: " + getChildCount());
        //测量孩子
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View itemView = getChildAt(i);
            if (itemView.getVisibility() != VISIBLE) {
                //不需要进行测量
                continue;
            }
            //测量前
            Log.i("chen", "测量前 高度--: " + itemView.getMeasuredHeight());
            measureChild(itemView, widthMeasureSpec, heightMeasureSpec);
            //测量后
            Log.i("chen", "测量后 高度--: " + itemView.getMeasuredHeight());
            if (line == null) {
                //说明当前行为空，可以添加进来
                line = createNewLine(itemView);
            } else {
                //判断是否可以再继续添加
                if (canBeAdd(itemView, line)) {
                    //可以添加进去
                    line.add(itemView);
                } else {
                    //新创建一行
                    line = createNewLine(itemView);
                }
            }
        }

        itemHeight = getChildAt(0).getMeasuredHeight();
        int selfHeight = (int) (lists.size() * itemHeight + mItemVerticalSpace * (lists.size() + 1) + 0.5f);
        //测量自己
        setMeasuredDimension(selfWidth, selfHeight);
    }

    private List<View> createNewLine(View itemView) {
        List<View> line = new ArrayList<>();
        line.add(itemView);
        lists.add(line);
        return line;
    }

    /**
     * 判断当前行是否可以再添加新数据
     *
     * @param itemView
     * @param line
     */
    private boolean canBeAdd(View itemView, List<View> line) {
        //所有的已添加的子view宽度加起来(line.size()+1)*mItemHorizontalSpace+itemView.getMeasuredWidth()
        //条件：如果小于/等于当前控件的宽度，则可以添加，否则不能添加
        int totalWidth = itemView.getMeasuredWidth();
        for (View view : line) {
            //叠加所有已添加控件的宽度
            totalWidth += view.getMeasuredWidth();
        }
        //水平间距的宽度
        totalWidth += mItemHorizontalSpace * (line.size() + 1);
        Log.i("chen", "totalWidth: " + totalWidth);
        //如果小于/等于当前控件的宽度，则可以添加，否则不能添加
        return totalWidth <= selfWidth;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //摆放孩子
        Log.i("chen", "摆放孩子: " + getChildCount());
        /*View itemOne = getChildAt(0);
        itemOne.layout(0, 0, itemOne.getMeasuredWidth(), itemOne.getMeasuredHeight());

        View itemTwo = getChildAt(1);
        itemTwo.layout(itemOne.getRight() + (int) mItemHorizontalSpace,
                0,
                itemOne.getRight() + (int) mItemHorizontalSpace + itemTwo.getMeasuredWidth(),
                itemTwo.getMeasuredHeight());*/

        int topOffset = (int) mItemVerticalSpace;
        for (List<View> list : lists) {
            //list是每一行
            int leftOffset = (int) mItemVerticalSpace;
            for (View view : list) {
                //每一行里的每个item
                view.layout(leftOffset, topOffset, leftOffset + view.getMeasuredWidth(), topOffset + view.getMeasuredHeight());
                leftOffset += view.getMeasuredWidth() + mItemHorizontalSpace;
            }
            topOffset += itemHeight + mItemVerticalSpace;
        }
    }

    public void setTextList(List<String> textList) {
        removeAllViews();
        this.mTextList.clear();
        this.mTextList.addAll(textList);
        //倒叙排列List
        Collections.reverse(this.mTextList);
        //遍历内容
        for (String text : mTextList) {
            //添加子View
            //TextView textView=new TextView(getContext());
            //LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view, this, true);
            //等价于
            TextView item = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view, this, false);
            item.setText(text);
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onFlowTextItemClickListener != null) {
                        onFlowTextItemClickListener.onFlowItemClick(text);
                    }
                }
            });
            addView(item);
            Log.i("chen", "子view: " + text);
        }
    }

    public void setOnFlowTextItemClickListener(OnFlowTextItemClickListener onFlowTextItemClickListener) {
        this.onFlowTextItemClickListener = onFlowTextItemClickListener;
    }

    public interface OnFlowTextItemClickListener {
        void onFlowItemClick(String text);
    }

    public int getContentSize() {
        return mTextList.size();
    }
}
